<?php
/**
 * Created By: ST2
 * Created on 2014-08-22 14:29:15
 * author: yongchao.yu@kunlun-inc.com
 * coding: utf-8
*/
namespace Melon\Database\Driver;

use Melon\Exception;
defined( 'IN_MELON' ) or die( 'Permission denied' );

class DbMysql extends Mysql {

	static protected $_linked = null; //是否连接

	public function __construct( $config = array() ) {
		if ( is_null(self::$_linked) ) {
			$db_host = $config['host'];
			$db_user = $config['username'];
			$db_passwd = $config['password'];
			$db_charset = $config['charset'];
			$db_name = $config['dbname'];
			$this->options['prefix'] = isset($config['prefix']) ? $config['prefix'] : '';
			$link = mysql_connect($db_host, $db_user, $db_passwd);

			if ( ! $link ) {
				throw new Exception\RuntimeException( '数据库连接失败' );
			} else {
				self::$_linked = $link;
				mysql_query('SET NAMES ' . $db_charset , $link);
			}
		} 
		$this->linkID = $link;
		mysql_select_db($db_name, $this->linkID);
	}

	/**
	 * 获取最后一次插入ID
	 * @return [type] [description]
	 */
	public function getInsertId() {
		return mysql_insert_id($this->linkID);
	}

	/**
	 * 获取影响的行数
	 * @return [type] [description]
	 */
	public function getAffectedRows() {
		return mysql_affected_rows($this->linkID);
	}

	/**
	 * 执行一个语句
	 * @param  [type] $sql [description]
	 * @return [type]      [description]
	 */
	public function execute( $sql = '' ) {
		if ( ! $this->linkID ) return false;
		//查询的sql语句
		$sql = empty($sql) ? $this->queryStr : $sql;
		// $this->queryStr = $sql;
        //释放前次的查询结果
        if ( is_resource($this->queryID) ) {    $this->free();    }

		$this->queryID = mysql_query($sql, $this->linkID);

		if (false === $this->queryID) {
			$this->error();
			return false;
		} else {
			$this->numRows = mysql_affected_rows($this->linkID);
			$this->lastInsID = mysql_insert_id($this->linkID);
			return $this->numRows;
		}
	}

    /**
     * 数据库错误信息
     * 并显示当前的SQL语句
     * @access public
     * @return string
     */
    public function error() {
        $this->error = mysql_errno().':'.mysql_error($this->linkID);
        if('' != $this->queryStr){
            $this->error .= "\n [ SQL语句 ] : ".$this->queryStr;
        }
        \Melon::debugWithTrace( $this->error );
        return $this->error;
    }

    /**
     * 读取一行数据到数组中
     * @return [type] [description]
     */
    public function fetch($result = null, $type = null) {
    	$result = is_null($result) ? $this->queryID : $result;
    	$type = is_null($type) ? 1 : 0;
    	$func = $type === 1 ? 'mysql_fetch_assoc' : 'mysql_fetch_object';
    	return $func($result);
    }


	/**
	 * 读取结果集中所有数据到数组中
	 * @return [type] [description]
	 */
	public function fetchAll() {
		$result = array();
        if($this->numRows >0) {

            while($row = mysql_fetch_assoc($this->queryID)){
                $result[]   =   $row;
            }
            // mysql_data_seek($this->queryID,0);
        }
        return $result;
	}

	/**
	 * 插入数据
	 * @param  [type]  $data    [插入的数据]
	 * @param  [type]  $table   [表名]
	 * @param  boolean $replace [description]
	 * @return [type]           [description]
	 */
	public function insert( $data, $table = null, $replace = false ) {
		$table = is_null( $table ) ? $this->table : $table;
		$sql = ($replace?'REPLACE':'INSERT'). " INTO `{$table}`";
		$fields = $values = array();
		$field = $value = '';
		//遍历记录, 格式化字段名称与值
		foreach($data as $key => $val){
		    $fields[] = $this->parseKey($key);
		    $values[] = is_numeric($val) ? $val : $this->parseValue($val);
		}

		$field = implode(',', $fields);
		$value = implode(',', $values);

		unset($fields, $values);
		$sql .= "({$field}) VALUES({$value})";
		$this->execute($sql);
		return $this->getInsertId();
	}

	/**
	 * 删除记录
	 * @param  [type] $table [表名]
	 * @param  [type] $where [条件]
	 * @return [type]        [影响行数]
	 */
	public function delete( $table = null, $where = null ) {
		$this->table = is_null($table) ? $this->table : $this->options['prefix'].$table;
		$where = is_null($where) ? (isset($this->options['where']) ? $this->options['where'] : null ) : $where;
		
		$this->queryStr = "DELETE FROM `{$this->table}` WHERE {$where}";
		//为了安全
		if ( is_null($where) && ! isset( $this->options['where'] ) ) {
			$this->error();
			return false;
		}

		$this->execute();
		return $this->getAffectedRows();
	}

	/**
	 * 数据更新
	 * @param  [type] $data  [更新数据]
	 * @param  [type] $where [where条件]
	 * @param  [type] $table [表名]
	 * @return [type]        [description]
	 */
	public function update( $data, $where = null, $table = null ) {
		$table = is_null($table) ? $this->table : $table;
		$where = is_null($where) ? @$this->options['where'] : $where;
		$sql = "UPDATE `{$table}` SET ";
		$values = array();
		foreach($data as $key => $val){  
            $val = is_numeric($val) ? $val : $this->parseValue($val);  
            $values[] = $this->parseKey($key) . " = {$val}";  
        }

        $value = implode(',', $values);
        $this->queryStr = $sql.$value . " WHERE {$where}";
        $this->execute();
        return $this->getAffectedRows();
	}

	/**
	 * 查询符合条件的所有记录
	 * @param  [type]  $where [description]
	 * @param  string  $field [description]
	 * @param  [type]  $table [description]
	 * @param  boolean $all   [description]
	 * @return [type]         [description]
	 */
	public function findAll( $table = null, $where = null, $field = '*',  $all = true ) {
		$this->options['where'] = is_null($where) ? $this->options['where'] : $where;
		$this->options['field'] = isset($this->options['field']) ? $this->options['field'] : $field;
		$this->options['table'] = is_null($table) ? $this->table : $this->options['prefix'] . $table;

		 $sql = "SELECT {$this->options['field']} FROM `{$this->options['table']}` ";  
        $sql .= isset($this->options['join']) ? ' LEFT JOIN '.$this->options['join']: '';  
        $sql .= isset($this->options['where']) ? ' WHERE '.$this->options['where']: '';  
        $sql .= isset($this->options['group']) ? ' GROUP BY '.$this->options['group']: '';  
        $sql .= isset($this->options['having']) ? ' HAVING '.$this->options['having']: '';  
        $sql .= isset($this->options['order']) ? ' ORDER BY '.$this->options['order']: '';  
        $sql .= isset($this->options['limit']) ? ' LIMIT '.$this->options['limit']: '';  
        $this->queryStr = $sql;
        $row = null;
        $this->execute();
        $row = $all === true ? $this->fetchAll() : $this->fetch();
        return $row;
	}

	/**
	 * 查询符合提交的一条记录
	 * @param  [type] $where [查询条件]
	 * @param  string $field [查询字段]
	 * @param  string $talbe [表]
	 * @return [type]        [description]
	 */
	public function find( $table = null , $where = null, $field='*' ) {
		return $this->findAll($table, $where, $field, false);
	}

    /**
     * 释放查询结果
     * @access public
     */
    public function free() {

    	if ( is_resource( $this->queryID ) ) {
    		echo 'shi';
    	}

        mysql_free_result( $this->queryID );
        $this->queryID = null;
    }


}